<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-03 10:09:27
 * @LastEditTime: 2023-02-16 10:39:53
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 合同文本
 * @Motto: Write the code. Change the world.
-->
<template>
  <div class="contract-text">
    <a-card title="生成合同文本" class="mb-20">
      <template #extra>
        <a-space>
          <a-button type="link" :disabled="!fileExist" @click="downloadFile">
            <template #icon>
              <DownloadOutlined />
            </template>
            下载
          </a-button>
          <a-button
            type="link"
            danger
            :disabled="!fileExist"
            @click="deleteFile"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            删除
          </a-button>
        </a-space>
      </template>
      <a-form layout="vertical">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-row :gutter="12" align="bottom">
              <a-col :span="18">
                <a-form-item label="选择模板">
                  <a-select v-model:value="template_id" placeholder="请选择">
                    <a-select-option
                      v-for="temp of templateList"
                      :value="temp.id"
                      :key="temp.id"
                    >
                      {{ temp.template_name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item>
                  <a-button :disabled="!template_id" @click="getFile"
                    >生成</a-button
                  >
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同文本">
              <a v-if="file.contractName" @click="previewUrl">{{
                file.contractName
              }}</a>
              <span v-else>--</span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card v-if="false">
      <a-row>
        <a-col :span="18">
          <a-button type="link">
            <span>--</span>
          </a-button>
        </a-col>
        <a-col :span="6" class="text-right">
          <a-space>
            <a-button type="link" :disabled="!fileExist">
              <template #icon>
                <DownloadOutlined />
              </template>
              下载
            </a-button>
            <a-button type="link" danger :disabled="!fileExist">
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
    <attachment-info
      :params="attachParams"
      @getObjectId="getObjectId"
      :active="$store.getters.currentStep == 2"
    />

    <!-- 预览合同 -->
    <ElectronContractModal
      :visible="electronContractVisible"
      :urlData="previewUrlData"
      :esignDetail="{
        esignCheck: true,
      }"
      title="在线预览"
      @close="electronContractVisible = false"
    />
  </div>
</template>

<script>
import moment from "moment";
import {
  computed,
  defineComponent,
  reactive,
  ref,
  watch,
  toRefs,
  toRaw,
  nextTick,
} from "vue";
import { DeleteOutlined, DownloadOutlined } from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import AttachmentInfo from "../../../components/contract/AttachmentInfo/index.vue";
import store from "../../../store";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { useRoute, useRouter } from "vue-router";
import ElectronContractModal from "../../../components/ElectronContractModal/index.vue";

const useForm = Form.useForm;

export default defineComponent({
  name: "ContractText",
  components: {
    DownloadOutlined,
    DeleteOutlined,
    AttachmentInfo,
    ElectronContractModal,
  },
  props: {
    trigger: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    const state = reactive({
      template_id: undefined,
      file: {},
      electronContractVisible: false,
      previewUrlData: {},
    });

    const fileExist = computed(() => {
      return !!state.file.contractName;
    });

    const $route = useRoute();
    const $router = useRouter();

    // 是否意向合同 或者 意向合同变更
    const isPurposeContract = computed(
      () => $route.query.contractType == "purposeContract" || $route.query.contractType == "purposeContractChange" || $route.query.contractType == "purposeContractEdit"
    );

    // 获取合同模板
    const templateList = ref([]);
    const currentBuildId = computed(() => store.getters.currentBuildId);
    const getTemplate = () => {
      if (!currentBuildId.value || !currentBuildId.value.length) {
        return;
      }
      request
        .post("/org", "/contract/printTemplate", {
          buildIds: currentBuildId.value,
          scene: isPurposeContract.value ? "purpose" : "normal",
        })
        .then((res) => {
          templateList.value = res.list;
          if (res.list.length) {
            let result = null;
            const { contractText } = store.getters.addFormData;
            if (state.template_id) {
              result = res.list.find((it) => it.id == state.template_id);
              if (!result) {
                state.template_id = undefined;
                state.file = {};
              }
            } else {
              if (contractText && contractText.apply_template_id) {
                result = res.list.find(
                  (item) => item.id == contractText.apply_template_id
                );
              }
              if (result) {
                state.template_id = result.id;
                state.file = contractText.apply_contract;
              }
            }
          } else {
            state.template_id = undefined;
            state.file = {};
          }
        });
    };

    const getFile = () => {
      const params = {
        template_id: state.template_id,
      };
      const { basicInfo, feeClause } = store.getters.addFormData;
      const contractData = {
        contract_number: basicInfo.contract_number,
        followup_uid: basicInfo.followup_uid,
        lease_square: basicInfo.lease_square,
        sign_time: basicInfo.sign_time,
        lease_starttime: basicInfo.lease_starttime,
        lease_endtime: basicInfo.lease_endtime,
        build_bind: basicInfo.build_bind,
        owner_id: basicInfo.owner_id,
        owner_info: basicInfo.owner_info,
        late_fee: basicInfo.late_fee,
        expense_clause: feeClause.expense_clause,
        extra_field: basicInfo.extra_field,
        org_branch_id: basicInfo.org_branch_id,
      };
      params.contractData = contractData;
      request.post("/org", "/create/printContract", params).then((res) => {
        state.file = res;
      });
    };

    const deleteFile = () => {
      utils.modalConfirm({
        content: "确认删除当前生成的合同文本吗？",
        okType: "danger",
        onOk: () => {
          if (editContractId.value) {
            request
              .get("/org", "/contract/delTemplate", {
                apply_template_id: state.template_id,
                contract_id: editContractId.value,
              })
              .then(() => {
                message.success("删除成功！");
                state.template_id = undefined;
                state.file = {};
              });
          } else {
            message.success("删除成功！");
            state.template_id = undefined;
            state.file = {};
          }
        },
      });
    };

    const downloadFile = () => {
      window.open(state.file.result.fileUrl);
    };

    const previewUrl = () => {
      state.previewUrlData = {
        previewUrl: state.file?.online_preview?.previewUrl,
        url: state.file?.result?.fileUrl,
      };
      state.electronContractVisible = true;
    };

    let objectId = "";
    const getObjectId = (id) => {
      objectId = id;
    };

    const validateForm = () => {
      let params = {
        object_id: objectId,
      };
      if (state.template_id) {
        params.apply_template_id = state.template_id;
        params.apply_contract = state.file;
      }
      store.dispatch("SetAddFormData", {
        key: "contractText",
        data: params,
      });
      context.emit("success");
    };

    const attachParams = ref({});

    const editContractId = computed(() => Number(store.getters.editContractId));

    const init = () => {
      const { contractText } = store.getters.addFormData;
      const attachInfo = {
        contract_id: editContractId.value,
      };
      if (contractText && contractText.object_id) {
        attachInfo.object_id = contractText.object_id;
      }
      attachParams.value = { ...attachInfo };
      getTemplate();
    };

    watch(
      () => props.trigger,
      (val) => {
        if (val) {
          validateForm();
        }
      }
    );
    watch(
      () => store.getters.currentStep,
      (step) => {
        if (step == 2) {
          init();
        }
      }
    );

    return {
      ...toRefs(state),
      fileExist,
      templateList,
      attachParams,
      getObjectId,
      getFile,
      deleteFile,
      downloadFile,
      previewUrl,
    };
  },
});
</script>
